package com.ruoyi.grpc;

import com.google.protobuf.InvalidProtocolBufferException;
import com.ruoyi.grpc.generate.AudioStreaming;
import io.grpc.Context;
import io.grpc.Contexts;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Base64;

/**
 * @author houhongbin
 * @date 2022/1/12
 */
public class AsrInterceptor implements ServerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AsrInterceptor.class);

    public static final String AUDIO_META = "audio_meta";

    public static final String EXTRA_INFO_KEY = "extra_info";

    public static final Context.Key<Object> EXTRA_INFO = Context.key(EXTRA_INFO_KEY);

    private static final Base64.Decoder DECODER = Base64.getDecoder();

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall,
                                                                 Metadata metadata,
                                                                 ServerCallHandler<ReqT, RespT> serverCallHandler) {
        String audioMeta = metadata.get(Metadata.Key.of(AUDIO_META, Metadata.ASCII_STRING_MARSHALLER));
        AudioStreaming.InitRequest initRequest = null;
        try {
            initRequest = AudioStreaming.InitRequest.parseFrom(DECODER.decode(audioMeta));
        } catch (InvalidProtocolBufferException e) {
            log.error("invalid protocol buffer, e=>", e);
        }
        log.debug("asr interceptor request extra info : {}", initRequest.getExtraInfo());
        Context context = Context.current().withValue(EXTRA_INFO, initRequest.getExtraInfo());
        return Contexts.interceptCall(context, serverCall, metadata, serverCallHandler);
    }
}
